package com.leyou.upload.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Service
public class UploadServiceImpl implements UploadService {


    @Autowired
    private FastFileStorageClient storageClient;//fastDFS访问的客户端对象

    Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);

    @Override
    public String uploadImage(MultipartFile file) {

        try {
            Set<String> set = new HashSet<>();

            set.add("image/jpeg");
            set.add("image/png");
//     校验文件类型
            String contentType = file.getContentType();
            if (!set.contains(contentType)) {
                logger.info("文件类型不匹配，{}请校验", contentType);
            }

//     校验文件内容
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                logger.info("文件内容不匹赔请校验");
            }
//     实现文件的逻辑上传
            String originalFilename = file.getOriginalFilename();
//            从字符串中最后一个，开始截取
            String s = StringUtils.substringAfterLast(originalFilename, ".");

//            输入流。文件大小，后缀名
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), s, null);

            return "http://image.leyou.com/" + storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
